﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BranchOfSansar.Sansar.Register;
using DevExpress.XtraEditors;

namespace BranchOfSansar.Register.Products
{
    public partial class frmRegProduct : Form
    {
        private List<ProductsEquipment> equips = new List<ProductsEquipment>();
        private List<ProductsItem> items = new List<ProductsItem>();
        private Product CurrProduct = null;
        private bool IsNew = false;
        private int oldProdCode;

        public frmRegProduct()
        {
            InitializeComponent();
            IsNew = true;
            CurrProduct = new Product();
            btnSave.Text = "Үүсгэх";
            Enable(false);
            using (BranchOfSansar.Sansar.Enquiry.EnquiryClient reg = new BranchOfSansar.Sansar.Enquiry.EnquiryClient(Globals.Token))
            {
                cmbType.Properties.Items.AddRange(reg.ProductTypes().Select(s => new BranchOfSansar.Sansar.Enquiry.ComboItem() { Display = s.Name, StrValue = s.ProdType }).ToArray());
                cmbType.SelectedIndex = 0;
                cmbStatus.SelectedIndex = 1;
                cmbAmountMonth.SelectedIndex = 1;
                txtNextProd.Properties.DisplayMember = "ProdCode";
                txtNextProd.Properties.ValueMember = "ProdCode";
                txtNextProd.Properties.DataSource = reg.Products("");
            }           
        }

        public frmRegProduct(Product prod)
            : this()
        {
            btnSave.Text = "Хадгалах";
            IsNew = false;
            CurrProduct = prod;
            txtInvoiceDay.Value = prod.InvoiceDay;
            txtName.Text = prod.Name;
            txtPrice.Text = prod.Price.ToString("#,##0");
            txtProdCode.Text = prod.ProdCode.ToString();
            oldProdCode=prod.ProdCode;
            cmbStatus.SelectedIndex = prod.Status ? 1 : 0;
            cmbAmountMonth.Text = prod.LengthOfAmount.ToString();
            cmbRealMonth.Text = prod.Length.ToString();
            Globals.setComboSelectedItem(cmbType, prod.ProdType);
            txtNextProd.EditValue = prod.NextProdCode.ToString();            
            txtProdCode.Enabled = false;
            txtUTMcode.Text = prod.UtmCode.ToString();
            Enable(true);
            using (RegisterClient reg = new RegisterClient(Globals.Token))
            {
                items = reg.ProductItems(prod.ProdCode).ToList();
                equips = reg.ProductEquipments(prod.ProdCode).ToList();
            }           
            
            BindItem();
            BindEquipment();
            btnSave.Enabled = false;
            
        }

        #region Private Methods
        private void Enable(bool value)
        {
            btnAddEquipment.Enabled = value;
            btnAddService.Enabled = value;
            btnDelEquipment.Enabled = value;
            btnDelService.Enabled = value;
            gridEquipment.Enabled = value;
            gridItem.Enabled = value;
        }

        private void BindItem()
        {
            FieldEditValueChanged(null, null);
            gridItem.DataSource = items;
            gridItem.RefreshDataSource();
            Calculate();
        }

        private void BindEquipment()
        {
            FieldEditValueChanged(null, null);
            gridEquipment.DataSource = equips;
            gridEquipment.RefreshDataSource();
            Calculate();
        }

        private void Calculate()
        {            
            decimal sum_item = items.Sum(s => s.Price );
            decimal sum_equips = equips.Sum(s => s.Price*s.Quantity);
            txtPriceOfItem.Text = sum_item.ToString("#,##0");
            txtPriceOfEquip.Text = sum_equips.ToString("#,##0");
            txtPrice.Text = (sum_item * cmbAmountMonth.SelectedIndex).ToString("#,##0");
        }
        #endregion

        private void btnAddService_Click(object sender, EventArgs e)
        {
            frmItem frm = new frmItem();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                items.Add(new ProductsItem()
                {
                    ProdCode = CurrProduct.ProdCode,
                    ItemCode = frm.SelectedItem.ItemCode,
                    Price = frm.SelectedItem.DefaultPrice,
                    ItemName = frm.SelectedItem.Name
                });
                BindItem();
            }
        }

        private void btnAddEquipment_Click(object sender, EventArgs e)
        {
            frmEquipment frm = new frmEquipment();
            if (frm.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
            {
                equips.Add(new ProductsEquipment()
                {
                    ProdCode = CurrProduct.ProdCode,
                    EquipCode = frm.SelectedEquipment.EquipCode,
                    Price = frm.SelectedEquipment.Price,
                    EquipmentName = frm.SelectedEquipment.Name,
                    Unit = frm.SelectedEquipment.Unit,
                    Quantity = 0
                });
                BindEquipment();
            }
        }

        private void btnDelEquipment_Click(object sender, EventArgs e)
        {

        }

        private void btnDelService_Click(object sender, EventArgs e)
        {
            if (viewItem.SelectedRowsCount < 1)
            {
                Globals.Warr("Өгөгдөл сонгогдоогүй байна!");
                return;
            }
            ProductsItem itm = (ProductsItem)viewItem.GetRow(viewItem.GetSelectedRows()[0]);
            items.Remove(itm);
            BindItem();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!Globals.DoValidation(pnlMain))
                return;
            if (txtNextProd.Text==txtNextProd.Properties.NullText)
            {
                Globals.Warr("Дараагийн шилжих бүтээгдэхүүний сонгоогүй байна!");
                return;
            }
                

            CurrProduct = new Product()
            {
                IsNewCustomer = chkIsNewCustomer.Checked,
                LengthOfAmount = byte.Parse(cmbAmountMonth.Text),
                Length = byte.Parse(cmbRealMonth.Text),
                Name = txtName.Text,
                Price = decimal.Parse(txtPrice.Text),
                ProdCode = int.Parse(txtProdCode.Text),
                ProdType = ((BranchOfSansar.Sansar.Enquiry.ComboItem)cmbType.SelectedItem).StrValue,
                InvoiceDay = (byte)txtInvoiceDay.Value,
                Status = cmbStatus.SelectedIndex == 1,
                NextProdCode = int.Parse(txtNextProd.Text),
                UtmCode=Convert.ToInt32(txtUTMcode.Text)
            };

            using (RegisterClient reg = new RegisterClient(Globals.Token))
            {
                Result res;
                if (IsNew)
                {
                    res = reg.AddProduct(CurrProduct);
                    if (res.Code == 0)
                    {
                        Globals.Info(res.Message);
                        Enable(true);
                        btnSave.Text = "Хадгалах";
                        btnSave.Enabled = false;
                        IsNew = false;
                    }
                    else
                        Globals.Warr(res.Message);
                }
                else
                {
                    res = reg.EditProduct(CurrProduct);
                    if (res.Code != 0)
                    {
                        Globals.Err(res.Message);
                        return;
                    }
                    res = reg.JoinItem(items.ToArray(), CurrProduct.ProdCode);
                    if (res.Code != 0)
                    {
                        Globals.Err(res.Message);
                        return;
                    }
                    res = reg.JoinEquip(equips.ToArray(), CurrProduct.ProdCode);
                    if (res.Code != 0)
                    {
                        Globals.Err(res.Message);
                        return;
                    }
                }
            }

            btnSave.Enabled = false;

        }

        private void viewItem_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            items = (List<ProductsItem>)viewItem.DataSource;
            FieldEditValueChanged(null, null);
        }

        private void FieldEditValueChanged(object sender, EventArgs e)
        {
            if (btnSave.Text != "Үүсгэх" && btnSave.Enabled == false)
            {
                btnSave.Enabled = true;                
            }
            Calculate();
        }

        private void frmRegProduct_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (btnSave.Enabled && btnSave.Text == "Хадгалах")
            {
                if (Globals.Question("Бүтээгдэхүүнд орсон өөрчлөлтийг хадгалах уу?") == System.Windows.Forms.DialogResult.Yes)
                {
                    btnSave_Click(sender, null);
                }
            }
        }

        private void frmRegProduct_Load(object sender, EventArgs e)
        {

        }

        private void viewEquipment_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            Calculate();
            FieldEditValueChanged(sender, e);
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {

        }

        private void txtUTMcode_EditValueChanged(object sender, EventArgs e)
        {
            if (btnSave.Text != "Үүсгэх" && btnSave.Enabled == false)
            {
                btnSave.Enabled = true;
            }
        }

       

    






    }
}
